<?php
if(!defined('FROM_INDEX'))exit('Invalid request');

require_once ROOT_PATH.'lib/baidu_bcs/conf.inc.php';
require_once ROOT_PATH.'lib/baidu_bcs/bcs.class.php';

function get_video_job_token()
{
	$request = array('grant_type'=>'client_credentials', 'client_id'=>'DGhyV4ewxIR5IwrdHzNUeag4', 'client_secret'=>'oC92hhZ356XtonbKiQl5LAdN1NTu41Gg');
	$result = post_request('https://openapi.baidu.com/oauth/2.0/token', $request);
	$json = parse_json($result);
	return (check_array($json) && isset($json['access_token'])) ? $json['access_token'] : '';
}

function create_video_job($input_name, $output_name, $token)
{
	$url = 'https://openapi.baidu.com/rest/2.0/media/v1/transcoding/job/create';
	$output = array('format'=>'mp4', 'h264_profile'=>'main',
   					'width'=>640, 'height'=>360, 'video_bitrate_bps'=>500*1000, 'max_frame_rate'=>30, 
   					'audio_channels'=>2, 'audio_sample_rate'=>44100, 'audio_bitrate_bps'=>128*1000);
	$request = array('access_token'=>$token, 'user_appid'=>'1341805',
   					'input_name'=>urlencode($input_name), 
   					'output_name'=>urlencode($output_name), 
   					'output'=>json_encode($output));
	$result = post_request($url, $request);
	
	return $result;
}

function save_to_bcs($obj_name, $obj_str, $meta='jpg')
{
	$url = '';

	if($obj_name && $obj_str)
	{
		$bucket = 'oye-bucket';
			
		$baidu_bcs = new BaiduBCS(BCS_AK, BCS_SK, 'bcs.duapp.com');
		try {
			create_bucket($baidu_bcs, $bucket);
			$result = create_object_by_content($baidu_bcs, $bucket, $obj_name, $obj_str);

			if ($result)
			{
				set_object_meta($baidu_bcs, $bucket, $obj_name, $meta);
			}

			if (is_object_exist($baidu_bcs, $bucket, $obj_name)) $url = "http://bcs.duapp.com/$bucket$obj_name";
		} catch (Exception $e) {
			//echo('--- Exception: '.$e->getMessage());
			return '';
		}
	}

	return $url;
}

function save_to_bcs_from_file($obj_name, $file_name)
{
	$url = '';

	if($obj_name && $file_name)
	{
		$bucket = 'oye-bucket';
			
		$baidu_bcs = new BaiduBCS(BCS_AK, BCS_SK, 'bcs.duapp.com');
		try {
			create_bucket($baidu_bcs, $bucket);
			$result = create_object($baidu_bcs, $file_name, $obj_name, $bucket);

//			if ($result)
//			{
//				set_object_meta($baidu_bcs, $bucket, $obj_name, $meta);
//			}

			if (is_object_exist($baidu_bcs, $bucket, $obj_name)) $url = "http://bcs.duapp.com/$bucket$obj_name";
		} catch (Exception $e) {
			//echo('--- Exception: '.$e->getMessage());
			return '';
		}
	}

	return $url;
}

function delete_from_bcs($obj_name)
{
	if ($obj_name)
	{
		$bucket = 'oye-bucket';
			
		$baidu_bcs = new BaiduBCS(BCS_AK, BCS_SK, 'bcs.duapp.com');
		try {
			if (is_object_exist($baidu_bcs, $bucket, $obj_name)) {
				delete_object($baidu_bcs, $bucket, $obj_name);
			}
		} catch (Exception $e) {
			//echo('--- Exception: '.$e->getMessage());
			return false;
		}
	}
}

function clear_bcs_dir($dir_name)
{
	if ($dir_name)
	{
		$bucket = 'oye-bucket';
			
		$baidu_bcs = new BaiduBCS(BCS_AK, BCS_SK, 'bcs.duapp.com');
		try {
			$response = $baidu_bcs->list_object_by_dir($bucket, $dir_name, 0, array('limit'=>1000));
			var_dump($response->body);
			$body = json_decode($response->body, true);
			$obj_list = $body['object_list'];
			
			var_dump($obj_list);
			foreach ($obj_list as $arr) {
				var_dump($arr['object']);
				delete_from_bcs($arr['object']);
			}
		} catch (Exception $e) {
			//echo('--- Exception: '.$e->getMessage());
			return false;
		}
	}
}

/**
 * ************************bucket********************************** *
 * */
function create_bucket($baidu_bcs, $bucket) {
	//	$acl = BaiduBCS::BCS_SDK_ACL_TYPE_PUBLIC_CONTROL;
	//	$acl = BaiduBCS::BCS_SDK_ACL_TYPE_PUBLIC_READ;
	//	$acl = BaiduBCS::BCS_SDK_ACL_TYPE_PUBLIC_READ_WRITE;
	//	$acl = BaiduBCS::BCS_SDK_ACL_TYPE_PUBLIC_WRITE;
	$acl = BaiduBCS::BCS_SDK_ACL_TYPE_PRIVATE;
	$response = $baidu_bcs->create_bucket ( $bucket, $acl );
	printResponse ( $response );
	
	return $response->isOK();
}

function delete_bucket($baidu_bcs, $bucket) {
	$response = $baidu_bcs->delete_bucket ( $bucket );
	printResponse ( $response );
	
	return $response->isOK();
}

/**
 * ************************object********************************** *
 * */

function bs_log($log) {
	trigger_error ( basename ( __FILE__ ) . " [time: " . time () . "][LOG: $log]" );
}

function create_object($baidu_bcs, $fileUpload, $object, $bucket) {
	$opt = array ();
	$opt ['acl'] = BaiduBCS::BCS_SDK_ACL_TYPE_PUBLIC_READ;
	$opt [BaiduBCS::IMPORT_BCS_LOG_METHOD] = "bs_log";
	$opt ['curlopts'] = array (
			CURLOPT_CONNECTTIMEOUT => 10, 
			CURLOPT_TIMEOUT => 1800 );
	$response = $baidu_bcs->create_object ( $bucket, $object, $fileUpload, $opt );
	printResponse ( $response );
	
	return $response->isOK();
}

function create_object_by_content($baidu_bcs, $bucket, $object, $content) {
	$opt = array ();
	$opt ['acl'] = BaiduBCS::BCS_SDK_ACL_TYPE_PUBLIC_READ;
	$opt [BaiduBCS::IMPORT_BCS_LOG_METHOD] = "bs_log";
	$opt ['curlopts'] = array (
			CURLOPT_CONNECTTIMEOUT => 10, 
			CURLOPT_TIMEOUT => 1800 );
	$response = $baidu_bcs->create_object_by_content( $bucket, $object, $content, $opt );
	printResponse ( $response );
	
	return $response->isOK();
}

function set_object_meta($baidu_bcs, $bucket, $object, $meta) {
	$meta = array (
			"Content-Type" => BCS_MimeTypes::get_mimetype ($meta) );
	$response = $baidu_bcs->set_object_meta ( $bucket, $object, $meta );
	printResponse ( $response );
	
	return $response->isOK();
}

function is_object_exist($baidu_bcs, $bucket, $object) {
	$bolRes = $baidu_bcs->is_object_exist ( $bucket, $object );
	//echo $bolRes == true ? "Object exist" : "Object not exist";
	return $bolRes == true;
}

function delete_object($baidu_bcs, $bucket, $object) {
	$response = $baidu_bcs->delete_object ($bucket, $object);
	printResponse ( $response );
	
	return $response->isOK();
}

function generate_get_object_url($baidu_bcs, $bucket, $object) {
	$opt = array ();
	$opt ["time"] = time () + 3600; //可选，链接生效时间为linux时间戳向后一小时 
	//$opt ["ip"] = "10.81.42.123"; //可选，限制本链接发起的客户端ip
	

	echo $baidu_bcs->generate_get_object_url ( $bucket, $object, $opt );
}

function generate_put_object_url($baidu_bcs, $bucket, $object) {
	$opt = array ();
	$opt ["time"] = time () + 3600; //可选，链接生效时间为linux时间戳向后一小时 
	$opt ["size"] = 1024 * 1024; //可选，用户上传时，限制上传大小，这里限制1MB
	//"ip" => "192.168.1.1"    //可选，限制本链接发起的客户端ip
	

	echo $baidu_bcs->generate_put_object_url ( $bucket, $object, $opt );
}

function generate_post_object_url($baidu_bcs, $bucket, $object) {
	$opt = array ();
	$opt ["time"] = time () + 3600; //可选，链接生效时间为linux时间戳向后一小时 
	$opt ["size"] = 1024 * 1024; //可选，用户上传时，限制上传大小，这里限制1MB
	//"ip" => "192.168.1.1"    //可选，限制本链接发起的客户端ip
	

	echo $baidu_bcs->generate_post_object_url ( $bucket, $object, $opt );
}

function printResponse($response) {
//	echo $response->isOK () ? "OK\n" : "NOT OK\n";
//	echo 'Status:' . $response->status . "\n";
//	echo 'Body:' . $response->body . "\n";
//	echo "Header:\n";
//	var_dump ( $response->header );
}